package com.xiaoying.server.publish.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;

import org.junit.Test;

public class SerializeUtil {
	
	/**
	 * 序列化
	 * @param object
	 * @return
	 */
	public static byte[] serialize(Object object) {
		 ObjectOutputStream oos = null;
		 ByteArrayOutputStream baos = null;
		 try{
			 //序列化
			 baos = new ByteArrayOutputStream();
			 oos = new ObjectOutputStream(baos);
			 oos.writeObject(object);
			 byte[] bytes = baos.toByteArray();
			 return bytes;
		 } catch (Exception e) {		  
			 e.printStackTrace();
		 }
		 return null;
	}

	/**
	 * 反序列化	  
	 * @param bytes
	 * @return
	 */
	public static Object unserialize(byte[] bytes) {
		 ByteArrayInputStream bais = null;
		 try {
			 //反序列化
			 bais = new ByteArrayInputStream(bytes);
			 ObjectInputStream ois = new ObjectInputStream(bais);
			 return ois.readObject();
		 } catch (Exception e) {		  
			 e.printStackTrace();
		 }
		 return null;
	}

	/**
	 * List<byte[]> 转换成 byte[]
	 * @param byteslist
	 * @return
	 * @author ZJD
	 */
	public static byte[] getBytesFromList(List<byte[]> byteslist) {
	    int byteLen = 0;
        for(byte[] bytesTmp:byteslist) {
            byteLen+= bytesTmp.length;
        }
        byte[] newBytes = new byte[byteLen];
        int destByteLen = 0;
        for(byte[] bytesTmp:byteslist) {
            System.arraycopy(bytesTmp, 0, newBytes, destByteLen, bytesTmp.length);  
            destByteLen += bytesTmp.length;  
        }
        return newBytes;
	}
	
	
	
	
}
